<?php

namespace apps\marriage\core\service;

use apps\marriage\core\model\MemberProfileExchangeApply;
use apps\marriage\core\model\ServiceChargeOrder;
use apps\marriage\core\model\SystemNotice;
use apps\marriage\core\model\UserPlatform;
use apps\marriage\core\model\UserSystemNotice;
use think\Exception;
use think\facade\Log;
use vm\com\BaseService;
use vm\org\queue\QueueFactory;

class MemberProfileExchangeApplyService extends BaseService
{

    /**
     * @return MemberProfileExchangeApply
     */
    protected function getModel()
    {
        return new MemberProfileExchangeApply();
    }

    /**
     * @return UserService
     */
    protected function getUserService()
    {
        return service('User', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|SiteConfigService
     */
    protected function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    /**
     * @return MemberProfileService
     */
    protected function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    /**
     * @return SystemNoticeService
     */
    protected function getSystemNoticeService()
    {
        return service('SystemNotice', SERVICE_NAMESPACE);
    }

    /**
     * @return UserSystemNoticeService
     */
    protected function getUserSystemNoticeService()
    {
        return service('UserSystemNotice', SERVICE_NAMESPACE);
    }

    /**
     * @return UserPlatformService
     */
    protected function getUserPlatformService()
    {
        return service('UserPlatform', SERVICE_NAMESPACE);
    }

    /**
     * @return ServiceChargeOrderService
     */
    protected function getServiceChargeOrderService()
    {
        return service('ServiceChargeOrder', SERVICE_NAMESPACE);
    }

    public function format(array $data)
    {
        switch ($data['type']) {
            case MemberProfileExchangeApply::TYPE_VIEW_WXID:
                $data['type_label'] = '查看微信号';
                break;

            case MemberProfileExchangeApply::TYPE_UNLOCK_PHONE:
                $data['type_label'] = '解锁手机号';
                break;

            default:
                break;
        }

        switch ($data['status']) {
            case MemberProfileExchangeApply::STATUS_AUDITING:
                $data['status_label'] = '审核中';
                break;

            case MemberProfileExchangeApply::STATUS_REJECT:
                $data['status_label'] = '申请被拒绝';
                break;

            case MemberProfileExchangeApply::STATUS_PASS:
                $data['status_label'] = '申请已通过';
                break;

            default:
                break;
        }

        return $data;
    }

    public function onAudit($id, $status, $remark = '')
    {
        $result = $this->updateByPk([
            'id' => $id,
            'status' => $status,
            'remark' => $remark,
            'audit_time' => time()
        ]);
        if(!$result) {
            throw new Exception('操作失败');
        }
        $apply = $this->getByPk($id);
        $apply = $this->format($apply);
        $applyUserId = $apply['apply_uid'];
        $applyMember = $this->getUserService()->getByPk($apply['apply_uid']);
        $applyMemberProfile = $this->getMemberProfileService()->getByUserId($apply['apply_uid']);

        $member = $this->getUserService()->getByPk($apply['member_uid']);
        $memberProfile = $this->getMemberProfileService()->getByUserId($apply['member_uid']);

        if($status == MemberProfileExchangeApply::STATUS_REJECT) {  // 将申请人支付的金币/人民币退还
            $params = [
                'iid' => $memberProfile['id']
            ];
            if($apply['type'] == MemberProfileExchangeApply::TYPE_VIEW_WXID) {
                $params['iid_type'] = ServiceChargeOrder::IID_TYPE_UNLOCK_MEMBER_WXID;
            } else if($apply['type'] == MemberProfileExchangeApply::TYPE_UNLOCK_PHONE) {
                $params['iid_type'] = ServiceChargeOrder::IID_TYPE_UNLOCK_MEMBER_PHONE;
            }
            $chargeOrder = $this->getServiceChargeOrderService()->info($params);
            if($chargeOrder) {
                $remark = '';
                if($apply['type'] == MemberProfileExchangeApply::TYPE_VIEW_WXID) {
                    $remark = '查看【'.$member['nick'].'】的微信号申请被拒绝';
                } else if($apply['type'] == MemberProfileExchangeApply::TYPE_UNLOCK_PHONE) {
                    $remark = '查看【'.$member['nick'].'】的手机号申请被拒绝';
                }
                if($chargeOrder['money_type'] == ServiceChargeOrder::MONEY_TYPE_GOLD_COIN) {
                    $this->getUserService()->increaseGoldCoin($applyUserId, $chargeOrder['order_money'], true, $remark);
                } else if($chargeOrder['money_type'] == ServiceChargeOrder::MONEY_TYPE_CNY) {
                    $this->getUserService()->increaseBalance($applyUserId, $chargeOrder['order_money'], true, $remark);
                }
                // 删除服务购买记录
                $this->getServiceChargeOrderService()->delete($params);
            } else {
                $field = '';
                if($apply['type'] == MemberProfileExchangeApply::TYPE_VIEW_WXID) {
                    $field = 'wxid_view_amount';
                } else if($apply['type'] == MemberProfileExchangeApply::TYPE_UNLOCK_PHONE) {
                    $field = 'phone_view_amount';
                }
                $this->getMemberProfileService()->increase($field, ['id' => $applyMemberProfile['id']]);
            }
        }

        // 给申请人发送通知
        $systemNoticeId = $this->getSystemNoticeService()->create([
            'title' => $apply['type_label'] . '处理结果',
            'content' => $apply['status_label'],
            'type' => SystemNotice::TYPE_SINGLE,
            'status' => SystemNotice::STATUS_PULLED,
            'recipient_id' => $applyUserId,
            'manager_id' => 0,
            'url' => json_encode([
                'weapp' => '/pages/member/profile?id=' . $memberProfile['id'],
                'web' => '/member_profile?id=' . $memberProfile['id'],
                'app' => '/member/profile?id=' . $memberProfile['id']
            ])
        ]);
        $this->getUserSystemNoticeService()->create([
            'system_notice_id' => $systemNoticeId,
            'recipient_id' => $applyUserId,
            'status' => UserSystemNotice::STATUS_WAIT_READ,
            'pull_time' => time()
        ]);

        // 给申请人发送公众号通知
        try {
            if($this->getUserPlatformService()->checkUserSubscribedMpAccount($applyUserId)) {
                $userPlatform = $this->getUserPlatformService()->info([
                    'user_id' => $applyUserId,
                    'platform' => UserPlatform::PLATFORM_WX_MP
                ]);
                if($userPlatform) {
                    $openid = $userPlatform['open_id'];
                    $wechatConfig = config('wechat');
                    $msgTemplateId = $wechatConfig['mp_msg_templates']['audit_result_notice'];
                    $msgData = [
                        'first' => [
                            'value' => $apply['type_label'] . '处理结果'
                        ],
                        'keyword1' => [
                            'value' => $member['nick']
                        ],
                        'keyword2' => [
                            'value' => $apply['status_label']
                        ],
                        'keyword3' => [
                            'value' => date('Y-m-d H:i:s')
                        ],
                        'remark' => [
                            'value' => '请点击链接查看'
                        ]
                    ];
                    $url = $this->getSiteConfigService()->getValueByCode('mp_site') . '/member_profile?id=' . $memberProfile['id'];
                    $miniprogram = null;

                    $queueConfig = config('queue');
                    $queueHandler = QueueFactory::instance();
                    $queueHandler->set($queueConfig['queues']['mp_msg'], [
                        'openid' => $openid,
                        'template_id' => $msgTemplateId,
                        'data' => $msgData,
                        'url' => $url,
                        'miniprogram' => $miniprogram
                    ]);
                }
            }
        } catch (\Exception $e) {
            $log = 'FILE:' . $e->getFile() . "\r\n" . 'LINE:' . $e->getLine(). "\r\n" . 'MSG:' . $e->getMessage();
            Log::error($log);
        }
    }
}